// Copyright 2010 The Walk Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package main

import (
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"path/filepath"
	"strings"
	"time"

	"walk"
	. "walk/declarative"
)

type MainWin struct {
	*walk.MainWindow
	le *walk.LineEdit
	wv *walk.WebView
}
var mainWin *MainWin
func main() {
	logFile, logErr := os.OpenFile("access.log", os.O_CREATE|os.O_RDWR, 0666)
	if logErr != nil {
		fmt.Println("Fail to find", *logFile, "cServer start Failed")
		os.Exit(1)
	}
	log.SetOutput(logFile)
	log.SetFlags(log.Ldate | log.Ltime | log.Lshortfile)

	mainWin, err := NewMainWin()
	if err != nil {
		log.Fatal(err)
	}

	mainWin.Run()
}

func NewMainWin() (*MainWin, error) {
	mainWin = new(MainWin)

	err := MainWindow{
		AssignTo: &mainWin.MainWindow,
		Icon:     Bind("'../img/' + icon(mainWin.wv.URL) + '.ico'"),
		Title:    "Walk WebView Example (With Events Printing)",
		MinSize:  Size{800, 600},
		Layout:   VBox{MarginsZero: true},
		Children: []Widget{
			LineEdit{
				AssignTo: &mainWin.le,
				Text:     Bind("wv.URL"),
				OnKeyDown: func(key walk.Key) {
					if key == walk.KeyReturn {
						mainWin.wv.SetURL(mainWin.le.Text())
					}
				},
			},
			WebView{
				AssignTo:                  &mainWin.wv,
				Name:                      "wv",
				URL:                       "file:///E:/GoMod/walk/examples/webview_events/web/test.html",
				ShortcutsEnabled:          true,
				NativeContextMenuEnabled:  true,


				OnNavigating:              mainWin.webView_OnNavigating,
				OnNavigated:               mainWin.webView_OnNavigated,
				OnDownloading:             mainWin.webView_OnDownloading,
				OnDownloaded:              mainWin.webView_OnDownloaded,
				OnDocumentCompleted:       mainWin.webView_OnDocumentCompleted,
				OnNavigatedError:          mainWin.webView_OnNavigatedError,
				OnNewWindow:               mainWin.webView_OnNewWindow,
				OnQuitting:                mainWin.webView_OnQuitting,
				OnWindowClosing:           mainWin.webView_OnWindowClosing,
				OnStatusBarVisibleChanged: mainWin.webView_OnStatusBarVisibleChanged,
				OnTheaterModeChanged:      mainWin.webView_OnTheaterModeChanged,
				OnToolBarVisibleChanged:   mainWin.webView_OnToolBarVisibleChanged,
				OnBrowserVisibleChanged:   mainWin.webView_OnBrowserVisibleChanged,
				OnCanGoBackChanged:        mainWin.webView_OnCanGoBackChanged,
				OnCanGoForwardChanged:     mainWin.webView_OnCanGoForwardChanged,
				OnToolBarEnabledChanged:   mainWin.webView_OnToolBarEnabledChanged,
				OnProgressChanged:         mainWin.webView_OnProgressChanged,
				OnStatusTextChanged:       mainWin.webView_OnStatusTextChanged,
				OnDocumentTitleChanged:    mainWin.webView_OnDocumentTitleChanged,
			},
			PushButton{
				Text:     "改写子窗口json文件",
				MaxSize:Size{90,40},
				OnClicked: ChangeText,
			},
		},
		Functions: map[string]func(args ...interface{}) (interface{}, error){
			"icon": func(args ...interface{}) (interface{}, error) {
				if strings.HasPrefix(args[0].(string), "https") {
					return "check", nil
				}

				return "stop", nil
			},
		},
	}.Create()

	return mainWin, err
}
func GetFullPath(objPath string) string  {
	ExeRoot, _ := filepath.Abs(objPath)
	return ExeRoot
}
func ChangeText()  {
	fileName := GetFullPath("web/json.js")
	fmt.Printf("文件路径:%+v\n",fileName)
	str :=`window.data='{"Type":2,"I_CodeKey":2510050,"StockName":"上证50ETF","F_Close":3.454,"F_Low":3.448,"I_FromOpen":225,"I_date":200709,"I_time":144347,"I_timeNumber":7,"Seed":0,"I_pznx":7,"F_Qrr":0.575,"F_LSR":1.016,"F_Hsl":4.241,"D_amount":24.5887,"F_ntg":168.253,"GaokaiRatio":-0.029,"FakeMoonNum":0,"LongSunNum":0,"WorstLsr":9.900,"MaxSunBs":1.649,"MaxMoonBs":-1.813,"TrendOfLsr":26.199,"TrendOfTwo":-0.010,"ChangeRatio":0.203,"SumOfDkh":-144.355,"DayM5":3.322,"DayM24":2.997,"RefClose":3.447,"HalfMoons":2,"Tactics":"","Timestamp":"%v"}';`
	newStr := fmt.Sprintf(str, time.Now())
	err := ioutil.WriteFile(fileName, []byte(newStr), 0644)
	if err != nil {
		fmt.Printf("重写文件时发生错误:%+v\n",err)
	}else {
		fmt.Println("重写文件完毕.")
	}
}
func (mainWin *MainWin) webView_OnNavigating(eventData *walk.WebViewNavigatingEventData) {
	log.Printf("webView_OnNavigating\r\n")
	log.Printf("Url = %+v\r\n", eventData.Url())
	log.Printf("Flags = %+v\r\n", eventData.Flags())
	log.Printf("PostData = %+v\r\n", eventData.PostData())
	log.Printf("Headers = %+v\r\n", eventData.Headers())
	log.Printf("TargetFrameName = %+v\r\n", eventData.TargetFrameName())
	log.Printf("Canceled = %+v\r\n", eventData.Canceled())
	// if you want to cancel
	//eventData.SetCanceled(true)
}

func (mainWin *MainWin) webView_OnNavigated(url string) {
	log.Printf("webView_OnNavigated\r\n")
	log.Printf("url = %+v\r\n", url)
}

func (mainWin *MainWin) webView_OnDownloading() {
	log.Printf("webView_OnDownloading\r\n")
}

func (mainWin *MainWin) webView_OnDownloaded() {
	log.Printf("webView_OnDownloaded\r\n")
}

func (mainWin *MainWin) webView_OnDocumentCompleted(url string) {
	log.Printf("webView_OnDocumentCompleted\r\n")
	log.Printf("url = %+v\r\n", url)
}

func (mainWin *MainWin) webView_OnNavigatedError(eventData *walk.WebViewNavigatedErrorEventData) {
	log.Printf("webView_OnNavigatedError\r\n")
	log.Printf("Url = %+v\r\n", eventData.Url())
	log.Printf("TargetFrameName = %+v\r\n", eventData.TargetFrameName())
	log.Printf("StatusCode = %+v\r\n", eventData.StatusCode())
	log.Printf("Canceled = %+v\r\n", eventData.Canceled())
	// if you want to cancel
	//eventData.SetCanceled(true)
}

func (mainWin *MainWin) webView_OnNewWindow(eventData *walk.WebViewNewWindowEventData) {
	log.Printf("webView_OnNewWindow\r\n")
	log.Printf("Canceled = %+v\r\n", eventData.Canceled())
	log.Printf("Flags = %+v\r\n", eventData.Flags())
	log.Printf("UrlContext = %+v\r\n", eventData.UrlContext())
	log.Printf("Url = %+v\r\n", eventData.Url())
	// if you want to cancel
	//eventData.SetCancel(true)
}

func (mainWin *MainWin) webView_OnQuitting() {
	log.Printf("webView_OnQuitting\r\n")
}

func (mainWin *MainWin) webView_OnWindowClosing(eventData *walk.WebViewWindowClosingEventData) {
	log.Printf("webView_OnWindowClosing\r\n")
	log.Printf("IsChildWindow = %+v\r\n", eventData.IsChildWindow())
	log.Printf("Canceled = %+v\r\n", eventData.Canceled())
	// if you want to cancel
	//eventData.SetCancel(true)
}

func (mainWin *MainWin) webView_OnStatusBarVisibleChanged() {
	log.Printf("webView_OnStatusBarVisibleChanged\r\n")
	log.Printf("StatusBarVisible = %+v\r\n", mainWin.wv.StatusBarVisible())
}

func (mainWin *MainWin) webView_OnTheaterModeChanged() {
	log.Printf("webView_OnTheaterModeChanged\r\n")
	log.Printf("IsTheaterMode = %+v\r\n", mainWin.wv.IsTheaterMode())
}

func (mainWin *MainWin) webView_OnToolBarVisibleChanged() {
	log.Printf("webView_OnToolBarVisibleChanged\r\n")
	log.Printf("ToolBarVisible = %+v\r\n", mainWin.wv.ToolBarVisible())
}

func (mainWin *MainWin) webView_OnBrowserVisibleChanged() {
	log.Printf("webView_OnBrowserVisibleChanged\r\n")
	log.Printf("BrowserVisible = %+v\r\n", mainWin.wv.BrowserVisible())
}

func (mainWin *MainWin) webView_OnCanGoBackChanged() {
	log.Printf("webView_OnCanGoBackChanged\r\n")
	log.Printf("CanGoBack = %+v\r\n", mainWin.wv.CanGoBack())
}

func (mainWin *MainWin) webView_OnCanGoForwardChanged() {
	log.Printf("webView_OnCanGoForwardChanged\r\n")
	log.Printf("CanGoForward = %+v\r\n", mainWin.wv.CanGoForward())
}

func (mainWin *MainWin) webView_OnToolBarEnabledChanged() {
	log.Printf("webView_OnToolBarEnabledChanged\r\n")
	log.Printf("ToolBarEnabled = %+v\r\n", mainWin.wv.ToolBarEnabled())
	log.Print()
}

func (mainWin *MainWin) webView_OnProgressChanged() {
	log.Printf("webView_OnProgressChanged\r\n")
	log.Printf("ProgressValue = %+v\r\n", mainWin.wv.ProgressValue())
	log.Printf("ProgressMax = %+v\r\n", mainWin.wv.ProgressMax())
}

func (mainWin *MainWin) webView_OnStatusTextChanged() {
	log.Printf("webView_OnStatusTextChanged\r\n")
	log.Printf("StatusText = %+v\r\n", mainWin.wv.StatusText())
	//log.Println("--------------------------------")
	//
	//log.Printf("mainWin.wv = %+v\r\n", mainWin.wv)
}

func (mainWin *MainWin) webView_OnDocumentTitleChanged() {
	log.Printf("webView_OnDocumentTitleChanged\r\n")
	log.Printf("DocumentTitle = %+v\r\n", mainWin.wv.DocumentTitle())
}
